import Vue from "vue";
import VueRouter from "vue-router";
import store from "@/store/store";

import Login from "@/view/Login";
Vue.use(VueRouter);
const allAuth = ["Admin", "User",'Manager'];
// const teacher = ["Admin",'Manager'];
const student = ["User"];
const routes = [
  {
    path: "/login",
    component: Login,
    meta: { title: "登录", roles: allAuth },
  },
  {
    path: "/home",
    redirect: "/home/message",
    component: () => import("@/view/Home"),
    children: [
      {
        path: "/home/test",
        meta: { title: "测试", roles: allAuth },
        component: () => import("@/components/Test"),
      },
      {
        path: "/home/apply",
        meta: { title: "实习申请", roles: student },
        component: () => import("@/components/InternshipApply/InternshipMain"),
      },
      {
        path: "/home/message",
        meta: { title: "消息列表", roles: allAuth },
        component: () => import("@/components/MessageList/MessageList"),
      },
      {
        path: "/home/group",
        meta: { title: "实习小组", roles: allAuth },
        component: () => import("@/components/IntemshipGroup/IntemshipGroup"),
      },
      {
        path: "/home/PersonalData",
        component: () => import("@/components/PersonalData"),
        meta: { title: "个人资料", roles: allAuth },
      },
      {
        path: "/404",
        component: () => import("@/view/404"),
        meta: { title: "404", roles: allAuth },
      },
    ],
  },
  {
    path: "*",
    component: () => import("@/view/error"),
    meta: { title: "错误", roles: allAuth },
  },
];

const router = new VueRouter({
  mode: "history",
  scrollBehavior: () => ({ y: 0 }),
  routes,
});
router.beforeEach((to, from, next) => {
  document.title = to.meta.title; //设置网页标题
  //如果是登录页面(无权限) 直接放行
  if (to.path == "/login") return next();

  //判断用户登录后保存到session的token以及存储的user信息（不存在 需要跳转login）
  const token = window.sessionStorage.getItem("token");
  if (!token || Object.keys(store.state.UserInfo).length == 0) {
    return next("/login"); //token不存在||user对象为空 强制跳转到登录页
  }

  //获取用户的角色做页面权限的管理 (用户角色不包含在路由配置的roles中跳转到404页面)
  const role = store.state.UserInfo.roleName;
  if (to.meta.roles.includes(role)) {
    next(); //放行
  } else {
    next("/404"); //跳到404页面
  }
});

export default router;
